package drds.plus.sql_process.type.impl;

import drds.plus.sql_process.type.*;

public class BooleanType extends CommonType<Boolean> {

    private final Calculator calculator = new AbstractCalculator() {

        public Object doAdd(Object v1, Object v2) {
            Boolean i1 = convert(v1);
            Boolean i2 = convert(v2);
            return (i1 ? 1 : 0) + (i2 ? 1 : 0);
        }

        public Object doSub(Object v1, Object v2) {
            Boolean i1 = convert(v1);
            Boolean i2 = convert(v2);
            return (i1 ? 1 : 0) - (i2 ? 1 : 0);
        }

        public Object doMultiply(Object v1, Object v2) {
            Boolean i1 = convert(v1);
            Boolean i2 = convert(v2);
            return (i1 ? 1 : 0) * (i2 ? 1 : 0);
        }

        public Object doDivide(Object v1, Object v2) {
            Boolean i1 = convert(v1);
            Boolean i2 = convert(v2);

            if (i2 == false) {
                return null;
            }

            return (i1 ? 1 : 0) / (i2 ? 1 : 0);
        }

        public Object doMod(Object v1, Object v2) {
            Boolean i1 = convert(v1);
            Boolean i2 = convert(v2);

            if (i2 == false) {
                return null;
            }
            return (i1 ? 1 : 0) % (i2 ? 1 : 0);
        }
    };

    public int encode(Object value, byte[] bytes, int offset) {
        Encoder.encode(this.convert(value), bytes, offset);
        return getLength(null);
    }

    public int getLength(Object value) {
        return 1;
    }

    public DecodeResult decode(byte[] bytes, int offset) {
        Boolean v = Decoder.decodeBooleanObj(bytes, offset);
        return new DecodeResult(v, getLength(v));
    }

    public Boolean incr(Object value) {
        throw new UnsupportedOperationException("boolean类型不支持incr操作");
    }

    public Boolean decr(Object value) {
        throw new UnsupportedOperationException("boolean类型不支持decr操作");
    }

    public Boolean getMaxValue() {
        return Boolean.TRUE; // 1代表true
    }

    public Boolean getMinValue() {
        return Boolean.FALSE; // 0代表false
    }

    public Calculator getCalculator() {
        return calculator;
    }

    public int getSqlType() {
        return java.sql.Types.BOOLEAN;
    }
}
